#include <string>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include "../adaptors.h"
#include "player.h"
using namespace std;
player::player()
{
    srand(time(0));
    played = false;
    f_random = false;
    f_repeat = false;
    curr_id = 0;
    engine_init();
}

player::~player()
{
	engine_free;
}

void player::play_begin(unsigned int id)
{
	Trec a = this->__playlist.get(id);
	if (a.duration != -1)
    {
        //deselect from Playlist/// bla-bla
      //  this->stop();
        hndl = engine_channel_create(a.f_path, false);
        cerr << "Now Playing file " << a.f_path   << " Length = " << engine_channel_getlength(hndl)<< endl;
        cerr << endl;
        curr_id = id;
        played = true;
    }
}

void player::pause()
{
    played = false;
    engine_channel_pause(hndl);
}

void player::stop()
{
    engine_channel_terminate(this->hndl);
    position = 0;
}

void player::next()
{
    unsigned int id = curr_id;
    played = true;
    if (!(this->f_random))
        id = rand() % __playlist.size();
    else
    {
        id = (id+ 1) % __playlist.size();
        if ((id == 0)&&(!this->f_repeat))
            played = false;
    }
    if (played)
        play_begin(id);

}

void player::previous()
{
    unsigned int id = curr_id;
    played = true;
    if (!(this->f_random))
        id = rand() % __playlist.size();
    else
    {
        id = (id - 1 + __playlist.size()) % __playlist.size();
        if ((id == (__playlist.size() - 1))&&(!this->f_repeat))
            played = false;
    }
    if (played)
        play_begin(id);
}

void player::play()
{
  play_begin(curr_id);
}
unsigned int player::selected_id()
{
    return curr_id;
}

float player::get_position()
{
  if (hndl != 0)
    return engine_channel_getlength(hndl);
  else
    return -1;
}

float player::get_cpu()
{
  return engine_get_cpu();
}


